package com.weixin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weixin.config.WeiXinProperties;
import com.weixin.entity.User;
import com.weixin.entity.dto.InviteDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjd
 * @Title:
 * @Description:
 * @date 2021/4/1216:01
 */
@Api("企业微信通讯录-成员管理")
@RestController
@RequestMapping("/v1.0/wei-xin/cgi-bin/user")
public class MemberController {
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private ObjectMapper objectMapper;


    @ApiOperation("创建成员")
    @PostMapping("/create")
    public ResponseEntity createUser(@RequestBody User user, HttpSession session) throws IOException, JSONException {
        String jsonStr = objectMapper.writeValueAsString(user);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/create?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = Integer.valueOf(String.valueOf(map.get("errcode")));
                if (integer==0){
                    return new ResponseEntity(map.get("errmsg"), HttpStatus.CREATED);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("根据userId获取成员信息")
    @GetMapping("/{userId}")
    public ResponseEntity getUserById(@PathVariable("userId") String userId, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/get?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&userid="+userId);
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = Integer.valueOf(String.valueOf(map.get("errcode")));
                if (integer==0){
                    return new ResponseEntity(map, HttpStatus.CREATED);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @ApiOperation("更新成员")
    @PutMapping("/update")
    public ResponseEntity updateUser(@RequestBody User user, HttpSession session) throws IOException, JSONException {
        String jsonStr = objectMapper.writeValueAsString(user);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/update?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = Integer.valueOf(String.valueOf(map.get("errcode")));
                if (integer==0){
                    return new ResponseEntity(map.get("errmsg"), HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("根据userId删除成员信息")
    @DeleteMapping("/{userId}")
    public ResponseEntity deleteByUserId(@PathVariable("userId") String userId, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/delete?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&userid="+userId);
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) map.get("errcode");
                if (integer==0){
                    return new ResponseEntity(map.get("errmsg"), HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("根据userId集合删除成员信息")
    @DeleteMapping()
    public ResponseEntity deleteByUserIds(@RequestParam("userIds") List<String> userIds, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("useridlist",userIds);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/batchdelete?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);

        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) resultMap.get("errcode");
                if (integer==0){
                    return new ResponseEntity(resultMap.get("errmsg"), HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(resultMap,HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @ApiOperation("根据departmentId查询成员集合")
    @GetMapping("/{departmentId}/userList")
    public ResponseEntity getUserByDepartmentId(@PathVariable("departmentId") String departmentId, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/simplelist?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&department_id="+departmentId);
        urlBuilder.append("&fetch_child="+0);

        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) map.get("errcode");
                if (integer==0){
                    return new ResponseEntity(map, HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("根据departmentId查询成员集合详细信息")
    @GetMapping("/{departmentId}/userListInfo")
    public ResponseEntity getUserByDepartmentIdUserInfo(@PathVariable("departmentId") String departmentId, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/list?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&department_id="+departmentId);
        urlBuilder.append("&fetch_child="+0);

        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) map.get("errcode");
                if (integer==0){
                    return new ResponseEntity(map, HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }




    @ApiOperation("根据userId转换为openId 需要成员使用微信登录企业微信或者关注微工作台才能获取openId")
    @GetMapping("/{userId}/convertToOpenid")
    public ResponseEntity convertToOpenid(@PathVariable("userId") String userId, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("userid",userId);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/convert_to_openid?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);

        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) resultMap.get("errcode");
                if (integer==0){
                    return new ResponseEntity(resultMap.get("openid"), HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(resultMap,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("根据openId转换为userId")
    @GetMapping("/{openId}/convertToUserid")
    public ResponseEntity convertToUserid(@PathVariable("openId") String openId, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("openid",openId);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/convert_to_userid?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);

        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) resultMap.get("errcode");
                if (integer==0){
                    return new ResponseEntity(resultMap.get("userid"), HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(resultMap,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation(" 二次验证如果成员是首次加入企业，企业获取到userid，并验证了成员信息后，调用如下接口即可让成员成功加入企业")
    @PutMapping("/{userId}")
    public ResponseEntity secondaryVerification(@PathVariable("userId") String userId, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/authsucc?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&userid="+userId);
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) map.get("errcode");
                if (integer==0){
                    return new ResponseEntity(map.get("errmsg"), HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @ApiOperation("企业可通过接口批量邀请成员使用企业微信，邀请后将通过短信或邮件下发通知。")
    @PostMapping("/batchInvite")
    public ResponseEntity batchInvite(@RequestBody InviteDto dto, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("user",dto.getUserIds());
        map.put("party",dto.getPartys());
        map.put("tag",dto.getTags());
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/batch/invite?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);

        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) resultMap.get("errcode");
                if (integer==0){
                    return new ResponseEntity(resultMap, HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(resultMap,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("支持企业用户获取实时成员加入二维码")
    @GetMapping("/getJoinQrcode")
    public ResponseEntity getJoinQrcode(HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/corp/get_join_qrcode?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&size_type="+" 171 x 171");
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) map.get("errcode");
                if (integer==0){
                    return new ResponseEntity(map, HttpStatus.OK);
                }
            }
        }
        return new ResponseEntity(map,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("获取企业活跃成员数 例如 2021-04-12 日期不能小于创建日期 也不能大当前时间")
    @GetMapping("/getActiveStat")
    public ResponseEntity getActiveStat(@RequestParam("date") String date, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("date",date);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/user/get_active_stat?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);

        return resultMap(resultMap,1);
    }

    private ResponseEntity resultMap(Map<String, Object> resultMap,Integer type){
        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) resultMap.get("errcode");
                if (integer==0){
                    ResponseEntity responseEntity = type==0 ? new ResponseEntity(resultMap.get("errmsg"), HttpStatus.OK): new ResponseEntity(resultMap, HttpStatus.OK);
                    return responseEntity;
                }
            }
        }
        return new ResponseEntity(resultMap,HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
